package com.nikmesoft.android.referendumfriend.activities;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.nikmesoft.android.referendumfriend.models.user;
import com.nikmesoft.android.referendumfriend.adapters.CropOptionAdapter;
import com.nikmesoft.android.referendumfriend.models.CropOption;
import com.nikmesoft.android.referendumfriend.utils.Utilities;
import com.nikmesoft.android.referendumfriend.R;

public class Profile_avarta extends BaseActivity {
	private ImageView ivavatar;

	private static final int TAKE_PHOTO_CODE = 100;
	private static final int PICK_PHOTO_CODE = 101;
	private static final int CROP_PHOTO_CODE = 102;
	private boolean flag_edit = false;
	private float AVATAR_SIZE = 60;
	private Bitmap selectedAvatar;
	private Uri mImageCaptureUri;
	private user user = new user();

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.avarta);
		ivavatar = (ImageView) findViewById(R.id.ivavatar);
		//Bundle extras = getIntent().getExtras();
		if (getIntent().getExtras() != null) {

			user.setAvatar(Utilities.getImage(getIntent().getExtras().getByteArray("avatar")));
			selectedAvatar = user.getAvatar();
			ivavatar.setImageBitmap(selectedAvatar);

			flag_edit = true;
		}
		AVATAR_SIZE = Utilities.dp2px(50.0f, this);
	}

	public void callBack(View view) {
		finish();
	}

	//public void callSave(View view) {
//		user newUser = new user();
//		if (selectedAvatar == null) {
//			selectedAvatar = Bitmap.createBitmap((int) AVATAR_SIZE,
//					(int) AVATAR_SIZE, Bitmap.Config.RGB_565);
//			Canvas canvas = new Canvas(selectedAvatar);
//			Drawable defaultAvatar = getResources().getDrawable(
//					R.drawable.no_avatar);
//			defaultAvatar.setBounds(0, 0, selectedAvatar.getWidth(),
//					selectedAvatar.getHeight());
//			defaultAvatar.draw(canvas);
//		}
//		newUser.setAvatar(selectedAvatar);
//
//		Intent data = new Intent();
//		if (flag_edit)
//			data.putExtra("id", newUser.getId());
//			data.putExtra("avatar", Utilities.getBytes(newUser.getAvatar()));
//		setResult(RESULT_OK, data);
//
//		finish();
//	}

	public void pickFromGallery(View v) {

		Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, PICK_PHOTO_CODE);
	}

	public void takeAPhoto(View v) {

		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		mImageCaptureUri = Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), "tmp_avatar_"
				+ String.valueOf(System.currentTimeMillis()) + ".jpg"));

		takePictureIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
				mImageCaptureUri);
		takePictureIntent.putExtra("return-data", true);
		startActivityForResult(takePictureIntent, TAKE_PHOTO_CODE);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case TAKE_PHOTO_CODE:
				doCrop();
				ivavatar.setImageBitmap(selectedAvatar);
				break;
			case PICK_PHOTO_CODE:
				mImageCaptureUri = data.getData();
				doCrop();
				ivavatar.setImageBitmap(selectedAvatar);
				break;
			case CROP_PHOTO_CODE:
				Bundle extras = data.getExtras();

				if (extras != null) {
					Bitmap bitmap = extras.getParcelable("data");
					ivavatar.setImageBitmap(bitmap);
					selectedAvatar = Utilities.getResizedBitmap(bitmap,
							(int) AVATAR_SIZE, (int) AVATAR_SIZE);
				}

				File f = new File(mImageCaptureUri.getPath());
				Log.d("PATH", mImageCaptureUri.getPath());
				if (f.exists()) {
					f.delete();
				}
				break;

			}

		}
	}

	private void doCrop() {
		final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();

		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setType("image/*");

		List<ResolveInfo> list = getPackageManager().queryIntentActivities(
				intent, 0);

		int size = list.size();

		if (size == 0) {
			// Utilities.toastNotify(this,
			// getString(R.string.crop_image_no_app));

			return;
		} else {
			intent.setData(mImageCaptureUri);

			intent.putExtra("outputX", 200);
			intent.putExtra("outputY", 200);
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("scale", true);
			intent.putExtra("return-data", true);

			if (size == 1) {
				Intent i = new Intent(intent);
				ResolveInfo res = list.get(0);

				i.setComponent(new ComponentName(res.activityInfo.packageName,
						res.activityInfo.name));

				startActivityForResult(i, CROP_PHOTO_CODE);
			} else {
				for (ResolveInfo res : list) {
					final CropOption cropoption = new CropOption();

					cropoption.title = getPackageManager().getApplicationLabel(
							res.activityInfo.applicationInfo);
					cropoption.icon = getPackageManager().getApplicationIcon(
							res.activityInfo.applicationInfo);
					cropoption.appIntent = new Intent(intent);

					cropoption.appIntent
							.setComponent(new ComponentName(
									res.activityInfo.packageName,
									res.activityInfo.name));

					cropOptions.add(cropoption);
				}

				CropOptionAdapter adapter = new CropOptionAdapter(this,
						R.layout.cropoption_item, cropOptions);

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("test");
				builder.setAdapter(adapter,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int item) {
								startActivityForResult(
										cropOptions.get(item).appIntent,
										CROP_PHOTO_CODE);
							}
						});

				builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
					public void onCancel(DialogInterface dialog) {

						if (mImageCaptureUri != null) {
							getContentResolver().delete(mImageCaptureUri, null,
									null);
							mImageCaptureUri = null;
						}
					}
				});

				AlertDialog alert = builder.create();

				alert.show();
			}
		}
	}

}
